#!/usr/bin/env python
# -*- coding:utf-8 -*-
from typing import List

from conn.MyLogs import MyLogs


# ***
# * 这个工具类主要处理数据表中针对dataL!这个固定标准表数据的读取与判断
# * Auth: tuut
# ***
class EgcDictUtil:
    SUCCESS = 200
    LOST_DATA = 400
    SYSTEM_ERROR = 500

    def __init__(self, conn):
        self.conn = conn
        return

    @staticmethod
    def make_json_key(payment_term, anb, currency, irr_anb, cash_payment_irr, accumulation_irr, saving,
                      repeat_saving_plan, repeat_saving_growth_rate, promotion, ):
        keys = [str(payment_term), str(anb), str(currency), str(irr_anb), str(cash_payment_irr),
                str(accumulation_irr), str(saving), str(repeat_saving_plan), str(repeat_saving_growth_rate),
                str(promotion), ]
        return '-'.join(keys)

    @staticmethod
    def get_json_key(json_key):
        return json_key.split("-")

    # **
    # 年期 单一计算单元年数
    # 供款期 判定基础数据来源
    def vlookup_EGC_by_anb_and_col(self, args: List[str], tab: str, col: str):
        year = args[0]
        anb = args[1]
        if year == 0:
            # return {"code": EgcDictUtil.SUCCESS, "data": 0}
            return 0
        try:
            # 1 数据查询 -----------------------------------------------------------------------------------
            fetch_sql = f" SELECT `{col}` FROM `EGC_HRACG` %s"
            where_sql = f' WHERE 1=1 '
            where_sql = where_sql + f' AND `TAB_NAME`= \'{tab}\''
            where_sql = where_sql + f' AND `ANB`= {year}'
            data_list = self.conn.sql_fetch(fetch_sql % where_sql)
            if len(data_list) > 0:
                # return {"code": EgcDictUtil.SUCCESS, "data": data_list[0][0]}
                return data_list[0][0]
            # {"code": EgcDictUtil.LOST_DATA, "data": None}
            return 0
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        # {"code": EgcDictUtil.SYSTEM_ERROR, "data": None}
        return 0

    @staticmethod
    def spow(n, m):
        res = 1
        for i in range(m):
            res *= n
        return res

    def insert_cal_json_data(self, args: List[str]) -> None:
        hkey = args[0]
        val_json = args[1]
        sys_time = args[2]
        try:
            fetch_sql = f"SELECT COUNT(1) FROM CAL_RAW_DATA WHERE `hkey` = \'{hkey}\'"
            check = self.conn.sql_fetch(fetch_sql)
            if check[0][0] > 0:
                return
            execute_sql = f" INSERT INTO CAL_RAW_DATA (hkey,val_json,sys_time) VALUES (\'%s\',\'%s\',\'%s\') "
            execute_sql = execute_sql % (hkey, val_json, sys_time)
            self.conn.sql_execute(execute_sql)
        except Exception as e:
            print(e)
